/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-04-08 17:17:15
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-05-27 09:09:48
 */
import React from "react";
import { Route, Redirect, Switch } from "react-router-dom";

const renderRoutes = (
  routes,
  authed,
  authPath = "/login",
  extraProps = {},
  switchProps = {}
) =>
  routes ? (
    <Switch {...switchProps}>
      {routes.map((route, i) => (
        <Route
          key={route.key || i}
          path={route.path}
          exact={route.exact}
          strict={route.strict}
          render={(props) => {
            if (!route.requiresAuth || authed || route.path === authPath) {
              return (
                <>
                  <route.component
                    exact={route.exact}
                    {...props}
                    {...extraProps}
                  ></route.component>
                  {route.children && (
                    <Switch>
                      {route.children.map((child, j) => {
                        return (
                          <Route
                            key={child.key || j}
                            path={child.path}
                            exact={child.exact}
                            strict={child.strict}
                            render={(childrenProps) => {
                              return (
                                <child.component
                                  {...childrenProps}
                                  {...extraProps}
                                ></child.component>
                              );
                            }}
                          />
                        );
                      })}
                    </Switch>
                  )}
                </>
              );

              // todo
              // return <route.component {...props} {...extraProps} route={route} />
            }
            return (
              <Redirect
                to={{ pathname: authPath, state: { from: props.location } }}
              />
            );
          }}
        />
      ))}
    </Switch>
  ) : null;

export default renderRoutes;
